<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    showFooter
    :title="getTitle"
    :minHeight="0"
    width="30%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { BasicForm, useForm } from '@/components/Form';
  import { editPasswordSchema } from './index.data';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { useMessage } from '@/hooks/web/useMessage';

  import { editPassword } from '@/api/system/user';
  import aes from '@/utils/aes';

  defineOptions({ name: 'Modal' });

  const { createMessage: msg } = useMessage();

  const emit = defineEmits(['success', 'register']);

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 90,
    schemas: editPasswordSchema,
    showActionButtonGroup: false,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setFieldsValue({
      ...data.record,
    });
  });

  const getTitle = '重置密码';

  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      values.oldPassword = aes.encrypt(values.oldPassword);
      values.newPassword = aes.encrypt(values.newPassword);
      const res = await editPassword(values);
      if (res.isSucceed) {
        msg.success('操作成功');
        closeModal();
        emit('success');
      }
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
